function show_msg(msg, callback, type) {
	var type = type || 'error';
	var callback = callback || function(){};
	var html = $('<div>\
		<div class="popup_bg"></div>\
		<iframe class="popup_cover"></iframe>\
		<div class="popup_alert center_fix">\
			<h3 class="popup_alert_title">操作失败</h3>\
			<div class="popup_alert_msg">'+msg+'</div>\
			<div class="popup_alert_btn"><a href="#" class="btn">确定</a></div>\
		</div>\
	</div>');
	$('.popup_alert', html).addClass('popup_'+type);
	if (type == 'success') {
		$('.popup_alert_title', html).html('操作成功');
	}

	$('.btn', html).click(function(){
		html.remove();
		callback();

		return false;
	});

	$('body').append(html);
	$(window).resize();
}

function loading(status) {
  var status = status || 'on';
  $('#loading').remove();
  if (status == 'on') {
    $('body').append('<div id="loading">\
    	<div class="popup_bg"></div>\
    	<iframe class="popup_cover"></iframe>\
    	<div class="popup_loading center_fix">读取中...</div>\
    </div>');
    $(window).resize();
  }
}

follow_lock = false;

$('.follow_btn').live('click', function(){
      var user_id = $(this).attr('action-data');
      var self = this;
      if (follow_lock) {
        return false;
      }        
        follow_lock = true;
      $.post(SITE_URL+'/ajax/weibo.html', { id:user_id, fl:"is"}, function(data){
      follow_lock = false;
	     if (data == '0') {
	        show_msg('请重新登录', function(){
	         location.href = SITE_URL+'/login.html';
	       });
	     }else{
	         $(self).addClass('follow_btn2').removeClass('follow_btn').html('已关注');
	     }
	  });

	    return false;
});


$('.follow_btn2').live('click', function(){
     var user_id = $(this).attr('action-data');
     var self = this;
     
     if (follow_lock) {
        return false;
     }
  
    if (!confirm('确认取消关注？')) {
        return false;
    }
    follow_lock = true;
            $.post(SITE_URL+'/ajax/weibo.html', { id:user_id, fl:"un"}, function(data){
            follow_lock = false;
	        if (data == '0') {
	          show_msg('请重新登录', function(){
	            location.href = SITE_URL+'/login.html';
	          });
	        }else{
	        	$(self).addClass('follow_btn').removeClass('follow_btn2').html('加关注');
	        }
	    });

    return false;
});



var tweet_box_lock = true;

function tweet_box(msg, hid) {
  loading();
  var hid = hid || 0;
  $.get(SITE_URL+'/ajax/update.html?hid='+hid, function(html){
    loading('off');
    html = $(html);
    if (msg) {
		$('textarea', html).val(msg);
    }
    $('textarea', html).limit(140, '.num > em');
    $('.btn2', html).click(function(){
      html.remove();

      return false;
    });
    

	$('.btn4', html).click(function(){
		var url = SITE_URL+'/ajax/update/save.html';
		var id = [];
		var hid = $('input[name=hid]', html).val();
		var text = $('textarea', html).val();
		var type = $('input[name=send_mod]:checked', html).val();
		var img = $('#file_info', html).val();
		var time_h = $('select[name=time_h] :selected').val();
		var time_i = $('select[name=time_i] :selected').val();
		
		$('.post_box_select_user a', html).each(function(){
			if ($(this).hasClass('select')) {
				id.push($(this).attr('action-data'));
			}
		});

		
		if (!$('textarea', html).val()) {
			show_msg('请填写内容！', function(){
				$('textarea', html).focus();
			});
			return false;
		}
		if (id.join(',') == '') {
		    show_msg('请选择用户进行发送');
		    return false;
		};
		url = url+'?uids='+id.join(',');
		var info = { text:text, type:type, img:img, time_h:time_h, time_i:time_i, year:pick_year, month:pick_month, day:pick_day, hid:hid };
		if (tweet_box_lock) {
		    tweet_box_lock = false;
		    loading();
		    $.post(url, { info :  info }, function(data){
		        tweet_box_lock = true;
		        loading('off');
        		show_msg('发布成功！', function(){
        	        html.remove();
    			}, 'success');
    		});
		};
		return false;
	});

    $('body').append(html);
  	$(window).resize();
  });
}

function retweet_box(msg, id, user_name) {
  $('div[node-type=feed_list_repeat]').empty().hide();
  $('#retweet_box').remove();
  var html = $('<div id="retweet_box"><div class="popup_bg"></div>\
  	<iframe class="popup_cover"></iframe>\
  	<div class="popup_box center_fix">\
  		<div class="popup_box_t"></div>\
  		<div class="popup_box_c">\
  			<h3 class="popup_box_title">转发微博</h3>\
  			<div class="post_box">\
  				<div class="f14 l24">'+msg+'</div>\
  				<div class="post_box_input_box_t"><span class="num">您还可以输入<em>140</em>字</span></div>\
  				<div class="post_box_input_box">\
  					<textarea id="tweet_content"></textarea>\
  					<div>\
  						<label class="mr20">\
  							<input type="checkbox">\
  							同时作为 '+user_name+' 的评论发布</label>\
  						<label>\
  					</div>\
  				</div>\
  			</div>\
  			<div class="popup_box_btn">\
  				<div class="post_btn"> <a href="#" class="ico1">表情</a> <a href="#" class="ico5">话题</a>\
  					<div class="post_win" style="left:-30px;display:none">\
  						<div class="post_win_t"></div>\
  						<a href="#" class="close">关闭</a>\
  						<div class="post_win_tab clearfix"><a href="#" class="current loding">loading...</a></div>\
  					</div>\
  				</div>\
  				<a href="#" class="btn6">转发</a><a href="#" class="btn2">取消</a></div>\
  		</div>\
  		<div class="popup_box_b"></div>\
  	</div>\
  </div>');

  $('.btn2', html).click(function(){
    html.remove();

    return false;
  });

  $('textarea', html).limit(140, '.num > em');
  
  
  $('.btn6', html).click(function(){
    loading();
    $.post(SITE_URL+'/ajax/retweet.html', {
      id : id,
      is_comment: parseInt($('input[type=checkbox]', html).is(':checked')),
      status: $('textarea', html).val()
    }, function(data){
      loading('off');
      $('.btn2', html).click();
    });
    return false;
  });

  $('body').append(html);
	$(window).resize();
}



(function(){

if (typeof window.realTime != "undefined") {
  return;
}

var realTime = {
  _lang : {},
  lang : 'auto',
  fixTime : null
};

realTime._lang['en'] = {
  month : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'Aguest', 'September', 'October', 'November','December'],
  week : ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
  secend : '%1 second ago',
  secends : '%1 seconds ago',
  minute : '%1 minute ago',
  minutes : '%1 minutes ago',
  hour : '%1 hour ago',
  hours : '%1 hours ago',
  yesterday : 'yesterday at %1',
  lastweek : '%1 at %2',
  longago : '%1 %2, %3 at %4'
};

realTime._lang['zh-cn'] = {
  month : ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
  week : ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
  secend : '%1 秒前',
  secends : '%1 秒前',
  minute : '%1 分钟前',
  minutes : '%1 分钟前',
  hour : '%1 小时前',
  hours : '%1 小时前',
  yesterday : '昨日%1',
  lastweek : '%1%2',
  longago : '%1%2日, %3 %4'
};

realTime.outPut = function(time) {

  function sprintf() {
    var args = arguments;
    if (args.length == 1) {
      return args[0];
    }
    var pattern = new RegExp("%([1-"+args.length+"])", "g");
    return args[0].replace(pattern, function(match, index) {
      return args[index];
    });
  }

  if (this.lang == 'auto') {
    this.lang = navigator.browserLanguage || navigator.language;
    this.lang = this.lang.toLowerCase();
  }

  var lang = this._lang[this.lang] || this._lang['en'];

  var m = lang.month,
      w = lang.week,
      d = new Date();

  time = parseInt(time);

  var delta = (this.fixTime || parseInt(d.getTime() / 1000)) - time;
  // if the time is below 0 then set 0
  delta = delta > 0 ? delta : 0;
  
  if (delta < 3600 * 24) {
    if (delta < 60) {// less then 1 minute
      if (delta > 1) {
        delta = sprintf(lang.secends, delta);
      } else {
        delta = sprintf(lang.secend, delta);
      }
    } else if (delta < 3600) {// less then 1 hour
      delta = parseInt(delta / 60);
      if (delta > 1) {
        delta = sprintf(lang.minutes, delta);
      } else {
        delta = sprintf(lang.minute, delta);
      }
    } else {// less then 1 day
      delta = parseInt(delta / 3600);
      if (delta > 1) {
        delta = sprintf(lang.hours, delta);
      } else {
        delta = sprintf(lang.hour, delta);
      }
    }
  } else {
    d.setTime(time * 1000);
    var t = [parseInt(d.getHours()), parseInt(d.getMinutes())];
    var alpha = t[0] > 12 ? (t[0] - 12)+':'+t[1]+' pm' : t[0]+':'+t[1]+' am';
    if (delta < 3600 * 48) {// less then 2 days
      delta = sprintf(lang.yesterday, alpha);
    } else if (delta < 3600 * 24 * 7) {// less then 1 week
      delta = sprintf(lang.lastweek, w[d.getDay()], alpha);
    } else {// more then 1 week
      delta = sprintf(lang.longago, m[d.getMonth()], d.getDate(), d.getFullYear(), alpha);
    }
  }

  return delta;
};

window.realTime = realTime;

})();


(function($){ 
     $.fn.extend({  
         limit: function(limit,element) {
			
			var interval, f;
			var self = $(this);
					
			$(this).focus(function(){
				interval = window.setInterval(substring,100);
			});
			
			$(this).blur(function(){
				clearInterval(interval);
				substring();
			});
			
			substringFunction = "function substring(){ var val = $(self).val();var length = val.length;if(length > limit){$(self).val($(self).val().substring(0,limit));}";
			if(typeof element != 'undefined')
				substringFunction += "if($(element).html() != limit-length){$(element).html((limit-length<=0)?'0':limit-length);}"
				
			substringFunction += "}";
			
			eval(substringFunction);
			
			
			
			substring();
			
        } 
    }); 
})(jQuery);

jQuery.fn.extend({
insertAtCaret: function(myValue){
  return this.each(function(i) {
    if (document.selection) {
      this.focus();
      sel = document.selection.createRange();
      sel.text = myValue;
      this.focus();
    }
    else if (this.selectionStart || this.selectionStart == '0') {
      var startPos = this.selectionStart;
      var endPos = this.selectionEnd;
      var scrollTop = this.scrollTop;
      this.value = this.value.substring(0, startPos)+myValue+this.value.substring(endPos,this.value.length);
      this.focus();
      this.selectionStart = startPos + myValue.length;
      this.selectionEnd = startPos + myValue.length;
      this.scrollTop = scrollTop;
    } else {
      this.value += myValue;
      this.focus();
    }
  })
}
});

var funGetSelected = function(element) {
    if (!window.getSelection) { 
        //IE浏览器
        return document.selection.createRange().text;
    } else {
        return element.value.substr(element.selectionStart, element.selectionEnd - element.selectionStart);
    }
}, funInsertTopic = function(textObj, TOPIC) {
    var topic = "#" + TOPIC + "#", value = textObj.value, index = value.indexOf(topic);
    if (index === -1) {
        //匹配
        funTextAsTopic(textObj, topic);
    } 
    value = textObj.value;
    index = value.indexOf(topic);
    if (textObj.createTextRange) {
        var range = textObj.createTextRange();
        range.moveEnd("character", -1 * value.length)           
        range.moveEnd("character", index + 5);
        range.moveStart("character", index + 1);
        range.select();    
    } else {
        textObj.setSelectionRange(index + 1, index + 5);
        textObj.focus();
    }
}, funTextAsTopic = function(textObj, textFeildValue) {
    textObj.focus();
    if (textObj.createTextRange) {
        var caretPos = document.selection.createRange().duplicate();
        document.selection.empty();
        caretPos.text = textFeildValue;
    } else if (textObj.setSelectionRange) {
        var rangeStart = textObj.selectionStart;
        var rangeEnd = textObj.selectionEnd;
        var tempStr1 = textObj.value.substring(0, rangeStart);
        var tempStr2 = textObj.value.substring(rangeEnd);
        textObj.value = tempStr1 + textFeildValue + tempStr2;
        textObj.blur();
    }
};


//显示视频
function showFlash( host, flashvar) {
	var flashAddr = {
		'youku.com' : 'http://player.youku.com/player.php/sid/FLASHVAR=/v.swf',
		'ku6.com' : 'http://player.ku6.com/refer/FLASHVAR/v.swf',
		'sina.com.cn' : 'http://vhead.blog.sina.com.cn/player/outer_player.swf?vid=FLASHVAR',
		'sohu.com' : 'http://v.blog.sohu.com/fo/v4/FLASHVAR',
		'tudou.com' : 'http://www.tudou.com/v/FLASHVAR',
		'music' : 'FLASHVAR',
		'flash' : 'FLASHVAR'
	};
	var videoFlash = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="430" height="400">'
        + '<param value="transparent" name="wmode"/>'
		+ '<param value="FLASHADDR" name="movie" />'
		+ '<embed src="FLASHADDR" wmode="transparent" allowfullscreen="true" type="application/x-shockwave-flash" width="430" height="400"></embed>'
		+ '</object>';
	var flashHtml = videoFlash;

	flashvar = encodeURI(flashvar);
	if(flashAddr[host]) {
		var flash = flashAddr[host].replace('FLASHVAR', flashvar);
		flashHtml = flashHtml.replace(/FLASHADDR/g, flash);
	}

	return flashHtml;
}
